package com.novel.download.controller;


import com.novel.download.controller.resp.CatalogueResp;
import com.novel.download.controller.resp.SearchResp;
import com.novel.download.service.NovelService;
import com.novel.download.utils.ReadBookUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RequestMapping("/novel")
@RestController
public class DownloadController {

    @Autowired
    private NovelService novelService;

    @GetMapping
    public Object home() {
        return searchStr();
    }

    public static String searchStr() {
        return searchStr("");
    }

    public static String searchStr(String bookName) {
        return "<form action=\"/novel/ping\">\n" +
                "<input type=\"submit\" value=\"测试\">\n" +
                "</form>" +
                "<form action=\"/novel/search\">\n" +
                "小说名称:<input type=\"text\" name=\"bookName\" value=\"" + bookName + "\">\n" +
                "<input type=\"submit\" value=\"搜索\">\n" +
                "</form><br><br><br>";
    }

    @GetMapping("/ping")
    public Object ping() {
        Map<String, Boolean> ping = novelService.ping();
        StringBuilder sb = new StringBuilder(searchStr());
        for (Map.Entry<String, Boolean> entry : ping.entrySet()) {
            String key = entry.getKey();
            Boolean value = entry.getValue();
            sb.append(key).append("\t\t:\t\t").append(value ? "成功" : "失败").append("<br><br>");
        }
        return sb.toString();
    }

    @GetMapping("/search")
    public Object search(@RequestParam(name = "bookName") String bookName) {
        Map<String, List<SearchResp>> res = novelService.search(bookName);
        return searchStr(bookName) + ReadBookUtils.searchRespToH5String(res);
    }

    @GetMapping("/catalogue")
    public String catalogue(@RequestParam(name = "url") String url, @RequestParam(name = "net") String net) {
        CatalogueResp catalogue = novelService.catalogue(url, net);
        return searchStr(catalogue.getBookName()) + catalogue.toH5String();
    }

    @SneakyThrows
    @GetMapping("/download")
    public HttpServletResponse download(HttpServletResponse response,
                                        @RequestParam(name = "url") String url,
                                        @RequestParam(name = "net") String net,
                                        @RequestParam(required = false, name = "from") String from) throws FileNotFoundException {
        novelService.download(url, from, net, response);
        return null;
    }

}
